package com.zy.cat.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSON;
import com.taobao.api.internal.util.StringUtils;
//import com.taobao.api.response.TbkDgVegasTljCreateResponse;
//import com.taobao.api.response.TbkDgVegasTljCreateResponse.RightsInstanceCreateResult;
import com.zy.cat.common.annotation.RedisSingle;
import com.zy.cat.common.config.Configs;
import com.zy.cat.common.utils.AesEncryptUtils;
import com.zy.cat.common.utils.CalculateUtil;
import com.zy.cat.common.utils.HdkAPI;
import com.zy.cat.common.utils.TBAPI;
import com.zy.cat.common.utils.TJKUtils;
import com.zy.cat.common.utils.WeiYiAPI;
import com.zy.cat.common.utils.dtk.DTKAPI;
import com.zy.cat.common.utils.sms.RYSMSUtils;
import com.zy.cat.dao.Dao;
import com.zy.cat.entity.dev.CatDevUserInfo;
import com.zy.cat.entity.dev.resp.CatDevUserInfoResp.TLJInfo;
import com.zy.cat.entity.dtk.GoodsDetail;
import com.zy.cat.entity.dtk.GoodsTopic.Opts;
import com.zy.cat.entity.dtk.resp.GoodsActivityListResp;
import com.zy.cat.entity.dtk.resp.GoodsActivityResp;
import com.zy.cat.entity.dtk.resp.GoodsListResp;
import com.zy.cat.entity.dtk.resp.GoodsNineResp;
import com.zy.cat.entity.dtk.resp.GoodsRankListResp;
import com.zy.cat.entity.dtk.resp.GoodsTopicListResp;
import com.zy.cat.entity.hdk.HdkGoodsItem;
import com.zy.cat.entity.mall.CatGoodsCouponHistory;
import com.zy.cat.entity.mall.TKTLJGoodsOrders;
import com.zy.cat.entity.mall.repository.CatGoodsCouponHistoryRepository;
import com.zy.cat.entity.mall.repository.TKTLJGoodsOrdersRepository;
import com.zy.cat.entity.mall.resp.CatBansResp;
import com.zy.cat.entity.mall.resp.CatDouYinVideoResp;
import com.zy.cat.entity.mall.resp.CatDynamicBannerResp;
import com.zy.cat.entity.mall.resp.CatGoodsCategoryResp;
import com.zy.cat.entity.mall.resp.CatHdkDuoyinResp;
import com.zy.cat.entity.mall.resp.CatHdkRatesUrlResp;
import com.zy.cat.entity.mall.resp.CatHomeTemplateResp;
import com.zy.cat.entity.mall.resp.CatTalentArticleResp;
import com.zy.cat.entity.mall.resp.CatTalentInfoResp;
import com.zy.cat.entity.mall.resp.FlashSaleGoodsResp;
import com.zy.cat.entity.mall.resp.TKSelectionResp;
import com.zy.cat.entity.mall.resp.TKTLJConvertResp;
import com.zy.cat.entity.mall.resp.TKTLJGoodsResp;
import com.zy.cat.entity.mall.resp.ZTKShopResp;
import com.zy.cat.entity.resp.Pages;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.entity.tb.resp.TKMaterialResp;
import com.zy.cat.entity.tb.resp.TKTQGResp;
import com.zy.cat.entity.wy.CatShopCouponInfo;
import com.zy.cat.entity.wy.CatShopCouponInfo.Data;
import com.zy.cat.entity.wy.CatShopItemResp;
import com.zy.cat.entity.wy.TKConvertResp;
import com.zy.cat.service.AsyncService;
import com.zy.cat.service.CacheService;
import com.zy.cat.service.CatMallService;

import lombok.extern.slf4j.Slf4j;



@Service
@Slf4j
public class CatMallServiceImpl implements CatMallService {

	@Autowired
	CacheService cacheService;

	@Autowired
	AsyncService asyncService;

	@Autowired
	Dao<TKTLJGoodsResp> gdao;

	@Autowired
	Dao<TLJInfo> tljDao;
	
	@Autowired
	Dao<Data> dataDao;

	@Autowired
	@Qualifier("redis9")
	RedisTemplate<String, String> redis9;

	@Autowired
	CatGoodsCouponHistoryRepository catGoodsCouponHistoryRepository;

	@Autowired
	TKTLJGoodsOrdersRepository tklJGoodsOrdersRepository;
	

	@Autowired
	Configs configs;

	@Override
	public List<CatBansResp> getBanners(Integer sex) {
		List<CatBansResp> banners = cacheService.getBanners(sex);
		return banners;
	}

	@Override
	public ResultPage<TKSelectionResp> getTodayTJList(int rtype, int sex, Pages pages) {
		return cacheService.getTodayTJList(rtype, sex, pages);
	}

	@Override
	public ResultPage<TKMaterialResp> getWLList(int rtype, String imei, int sex, int materialId, Pages pages) {
		// 组装key
		String key = rtype + "_" + imei + "_" + sex + "_" + materialId + "_" + pages.getPageNum() + "_"
				+ pages.getPageSize();
		return cacheService.getWLList(DigestUtils.md5DigestAsHex(key.getBytes()), (long) materialId, imei, pages);
	}

	@Override
	public List<TKTQGResp> getTQGList(int rtype, String stime, Pages pages) {
		String key = rtype + "_" + stime + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		return cacheService.getTQGList(DigestUtils.md5DigestAsHex(key.getBytes()), stime, pages);
	}

	@Override
	public TKConvertResp getGoodsConvert(Integer ctype, int rtype, int ftype, String vscode, String cid, String imei,
			String imsi, long fcode, String sid, String rid, String pid) {
		int type = 10;
//		 if(ctype==null) {
		ctype = 0;
//		 }
		type = (ctype + 1) * 10 + rtype;
		WeiYiAPI api = WeiYiAPI.getInstance(type);
//		WeiYiAPI api=WeiYiAPI.getInstance(rtype+10);

		if (ftype != -1) {
			asyncService.setGoodsSubsidyHistory(rtype, ftype, pid, rid, sid, fcode);
		}
		// 调用高佣转链API
		TKConvertResp tkConvert = api.getTKConvert(sid, rid);
		// 如果有券则添加到用户优惠券列表
		if (tkConvert.getResult() == 1) {
			asyncService.setGoodsCouponHistory(ftype, pid, tkConvert);
		}
		return tkConvert;
	}

	@Override
	public GoodsDetail getGoodsDetail(int rtype, String sid) {
		GoodsDetail goodsDetail = cacheService.getGoodsDetail(sid);
		if (goodsDetail != null && goodsDetail.getData() != null) {
			// 查询抖音数据
			goodsDetail.getData().setDouYinData(getHdkDuoyinItems(sid, 1));
		}
		return goodsDetail;
	}

	@Override
	public GoodsNineResp getGoodsNine(int rtype, int nineCid, String pageId, int pageSize) {
		String key = rtype + "_" + nineCid + "_" + pageId + "_" + pageSize;
		return cacheService.getGoodsNine(DigestUtils.md5DigestAsHex(key.getBytes()), nineCid, pageId, pageSize);
	}

	@Override
	public List<GoodsRankListResp> dtkRankList(int ctype, int rtype, String cat) {
		String key = ctype + "_" + rtype + "_" + cat;
		return cacheService.dtkRankList(DigestUtils.md5DigestAsHex(key.getBytes()), ctype, cat);
	}

	@Override
	public ResultPage<GoodsListResp> search(int isCoupon, int rtype, int stype, String pageId, Integer pageSize,
			String sword, int otype) {
		ResultPage<GoodsListResp> resultResp;

		String sort;
		if (otype == 1) {
			sort = "total_sales_asc";
		} else if (otype == 2) {
			sort = "total_sales_des";
		} else if (otype == 3) {
			sort = "price_asc";
		} else {
			sort = "price_des";
		}
		sword = sword.trim();
		// 判断是否为淘口令
		String pattern = "([\\p{Sc}])\\w{8,12}([\\p{Sc}])";
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(sword);
		// 如果为淘口令则直接调用转链接口查询商品信息
		if (m.find() && pageId.equals("1")) {
			GoodsListResp resp = searchTbWord(rtype, sword);
			// 修改是否含商品标题，此处是中文输入的【】
			Matcher mat = Pattern.compile("\\【([^}]*)\\】").matcher(sword);
			// 如果未查询到标题则直接返回
			if (!mat.find()) {
				resultResp = new ResultPage<>(Integer.parseInt(pageId), pageSize);
				resultResp.setTotal(resp == null ? 0 : 1);
				resultResp.setList(resp == null ? null : Arrays.asList(resp));
//				return resultResp;
			} else {
				DTKAPI api = DTKAPI.getInstance(0);
				sword = mat.group(1);
				resultResp = api.searchGoods(String.valueOf(stype), sword, sort, pageId, pageSize);
				if (resultResp.getList() != null && resp != null) {
					resultResp.getList().set(0, resp);
				} else if (resp != null) {
					resultResp.setList(resp == null ? null : Arrays.asList(resp));
				}
//				return resultResp;
			}
		} else {
			DTKAPI api = DTKAPI.getInstance(0);
			resultResp = api.searchGoods(String.valueOf(stype), sword, sort, pageId, pageSize);
		}
		if (isCoupon == 1 && resultResp != null && resultResp.getList() != null) {
			resultResp.setList(resultResp.getList().stream().filter(new Predicate<GoodsListResp>() {
				@Override
				public boolean test(GoodsListResp t) {
					return t.getCouponPrice() > 0;
				}
			}).collect(Collectors.toList()));
		}
		return resultResp;
	}

	/**
	 * 搜索淘口令
	 * 
	 * @author lipengchao
	 * @date 2019-12-10 10:34:55
	 * @param rtype
	 * @param sword
	 * @return
	 */
	private GoodsListResp searchTbWord(int rtype, String sword) {
		WeiYiAPI wyapi = WeiYiAPI.getInstance(10);
		TKConvertResp object = wyapi.getTKConvert(sword, "");
		if (object == null || object.getData() == null || object.getError() != 0) {
			return null;
		}
		GoodsListResp resp = JSON.parseObject(JSON.toJSONString(object.getData()), GoodsListResp.class);

		// 优惠卷金额
		double couponAmount = 0;
		double zkFinalPrice = Double.parseDouble(object.getData().getZk_final_price());
		if (!StringUtils.isEmpty(object.getData().getCoupon_info())) {
			String[] couponInfo = object.getData().getCoupon_info().replaceAll("[^(0-9)]", " ").trim()
					.replace("  ", " ").split(" ");
			if (zkFinalPrice >= Double.parseDouble(couponInfo[0])) {
				couponAmount = Double.parseDouble(couponInfo[1]);
			}
		}
		DecimalFormat df = new DecimalFormat("#.00");
		double rate = Double.parseDouble(object.getData().getCommission_rate());
		resp.setActualPrice(
				Double.parseDouble(df.format(Double.valueOf(object.getData().getZk_final_price()) - couponAmount)));
		resp.setFcode(CalculateUtil.getRebateAmount(zkFinalPrice, couponAmount, rate));
		resp.setCouponPrice(couponAmount);
		resp.setCouponStatus(object.getResult() == 1 ? 1 : 0);
		resp.setOriginalPrice(Double.parseDouble(object.getData().getZk_final_price()));
		resp.setMonthSales(Long.parseLong(object.getData().getVolume()));
		resp.setShopType(Integer.parseInt(object.getData().getUser_type()));
		resp.setGoodsId(object.getData().getNum_iid());
		resp.setMainPic(object.getData().getPict_url());
		resp.setShopName(object.getData().getNick());
		return resp;
	}

	@Override
	public List<String> hotSearch(int rtype, Integer pageNum, Integer pageSize) {
		List<String> respList = null;
		List<String> result = cacheService.hotSearch();
		if (pageNum == null || pageSize == null) {
			return result;
		}
		int startIndex = (pageNum - 1) * pageSize;
		if (result.size() <= startIndex) {
			respList = new ArrayList<>();
		} else if ((result.size() - startIndex) <= pageSize) {
			respList = result.subList(startIndex, result.size());
		} else {
			respList = result.subList(startIndex, startIndex + pageSize);
		}
		return respList;
	}

	@Override
	public List<Map<String, Object>> getSearchWord(int rtype, int stype, String kw) {
		String key = stype + "_" + kw;
		return cacheService.getSearchWord(DigestUtils.md5DigestAsHex(key.getBytes()), stype, kw);
	}

	@Override
	public List<GoodsListResp> getGoodsLike(int rtype, String imei, String imsi, String sid, int size) {
		String key = rtype + "_" + imei + "_" + imsi + "_" + sid + "_" + size;
		return cacheService.getGoodsLike(DigestUtils.md5DigestAsHex(key.getBytes()), sid, size);
	}

	@Override
	public ResultPage<GoodsListResp> dtkGoodsList(int rtype, String cat, String subcat, int otype, Pages pages) {
		String key = rtype + "_" + cat + "_" + subcat + "_" + otype + "_" + pages.getPageNum() + "_"
				+ pages.getPageSize();
		return cacheService.dtkGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), cat, subcat, otype, pages);
	}

	@Override
	public List<Opts> getGoodsTopic() {
		return cacheService.getGoodsTopic();
	}

	@Override
	public GoodsTopicListResp getGoodsTopicList(int rtype, int pageSize, String topicId, String pageId) {
		String key = rtype + "_" + topicId + "_" + pageId + "_" + pageSize;
		return cacheService.getGoodsTopicList(DigestUtils.md5DigestAsHex(key.getBytes()), topicId, pageId, pageSize);
	}

	@Override
	public GoodsActivityResp getActs(int rtype) {
		return cacheService.getActs();
	}

	@Override
	public GoodsActivityListResp getActsGoodsList(int rtype, int pageSize, String pageId, String actId) {
		String key = rtype + "_" + pageSize + "_" + pageId + "_" + actId;
		return cacheService.getActsGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), actId, pageId, pageSize);
	}

	@Override
	public ResultPage<TKSelectionResp> getZoroGoodsList(int rtype, String cid, int sex, Pages pages) {
		String key = rtype + "_" + cid + "_" + sex + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		return cacheService.getZoroGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), cid, sex, pages);
	}

	@Override
	public ResultPage<TKSelectionResp> getThreeGoodsList(int rtype, String cid, int sex, Pages pages) {
		String key = rtype + "_" + cid + "_" + sex + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		return cacheService.getThreeGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), cid, sex, pages);
	}

	@Override
	public ResultPage<TKSelectionResp> getFifteenGoodsList(int rtype, String cid, int sex, Pages pages) {
		String key = rtype + "_" + cid + "_" + sex + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		return cacheService.getFifteenGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), cid, sex, pages);
	}

	@Override
	public ResultPage<TKSelectionResp> getDailySurpriseGoodsList(Integer rtype, String cid, Integer sex, Pages pages) {
		String key = rtype + "_" + cid + "_" + sex + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		return cacheService.getDailySurpriseGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), cid, sex, pages);
	}

	@Override
	public List<Map<String, String>> getFavoritesList(String type) {
		// 0元购，选品库
		String[] zoroGoods = { "精选-19998776", "服装配饰-19998774", "食品-19998773", "个护-19998772", "数码-19998771",
				"百货-19998770" };
		// 3元购，选品库
		String[] threeGoods = { "精选-19998763", "百货-19998769", "数码-19998768", "个护-19998766", "食品-19998765",
				"男装-19998764" };
		// 15元购，选品库
		String[] fifteenGoods = { "精选-20039647", "百货-20039648", "数码-20039650", "个护-20039649", "食品-20039651",
				"服装配饰-20039686" };
		// 每日惊喜，选品库
		String[] dailySurpriseGoods = { "提前购-19997332", "品质母婴-19997331", "鞋包配饰-19997329", "休闲食品-19997328",
				"美妆洗护-19997327", "百货家清-19997325", "爆款尖货-19997324" };

		String[] goodsIdArray = null;
		if ("0".equals(type)) {
			goodsIdArray = zoroGoods;
		} else if ("1".equals(type)) {
			goodsIdArray = threeGoods;
		} else if ("2".equals(type)) {
			goodsIdArray = dailySurpriseGoods;
		} else if ("3".equals(type)) {
			goodsIdArray = fifteenGoods;
		} else {
			goodsIdArray = new String[0];
		}
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		Arrays.stream(goodsIdArray).forEach(item -> {
			Map<String, String> map = new HashMap<>();
			String[] split = item.split("-");
			map.put("cname", split[0]);
			map.put("cid", split[1]);
			list.add(map);
		});
		return list;
	}

	@Override
	public List<ZTKShopResp> getShopLike(Integer rtype, String imei, String imsi, String sid, String idfa, int page,
			int pageSize) {
		String key = rtype + "_" + imei + "_" + imsi + "_" + sid + "_" + idfa + "_" + page;
		return cacheService.getZTKShopLike(DigestUtils.md5DigestAsHex(key.getBytes()), imei, sid, idfa, page, pageSize);
	}

	@Override
	public ResultPage<TKSelectionResp> getBannerGoodsList(Integer rtype, String fid, Pages pages) {
		String key = rtype + "_" + fid + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		return cacheService.getBannerGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), fid, pages);
	}

	@Override
	public List<FlashSaleGoodsResp> getFlashSaleGoodsList(Integer rtype) {
		return cacheService.getFlashSaleGoodsList(LocalDate.now().toString());
	}

	@Override
	public ResultPage<TKSelectionResp> getFlashLowerGoodsList(Integer rtype, Integer sex, Pages pages) {
		String key = rtype + "_" + sex + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		return cacheService.getFlashLowerGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), sex, pages);
	}

	@Override
	public Boolean getFlashSaleGoods(Integer rtype, String pid, String sid) {
		return cacheService.rushToBuySaleGoods(pid, sid);
	}

	@Override
	public List<TKSelectionResp> getGoodsCouponList(Integer rtype, String pid) {
		List<CatGoodsCouponHistory> list = catGoodsCouponHistoryRepository.findByPid(pid);
		if (list == null) {
			return null;
		}
		List<TKSelectionResp> resultList = list.stream().map(object -> {
			TKSelectionResp selectionResp = JSON.parseObject(JSON.toJSONString(object), TKSelectionResp.class);
			// 优惠卷金额
			double couponAmount = 0;
			double zkFinalPrice = Double.parseDouble(object.getZkFinalPrice());
			if (!StringUtils.isEmpty(object.getCouponInfo())) {
				String[] couponInfo = object.getCouponInfo().replaceAll("[^(0-9)]", " ").trim().replace("  ", " ")
						.split(" ");
				if (zkFinalPrice >= Double.parseDouble(couponInfo[0])) {
					couponAmount = Double.parseDouble(couponInfo[1]);
				}
			}
			DecimalFormat df = new DecimalFormat("#.00");
			double rate = object.getCommissionRate();
			selectionResp.setActualPrice(df.format(Double.valueOf(object.getZkFinalPrice()) - couponAmount));
			selectionResp.setFcode(CalculateUtil.getRebateAmount(zkFinalPrice, couponAmount, rate));
			selectionResp.setCouponAmount(String.valueOf(couponAmount));
			return selectionResp;
		}).collect(Collectors.toList());
		return resultList;
	}

	@Override
	public ResultPage<TKSelectionResp> getSupercouponGoodsList(Integer rtype, Pages pages) {
		String key = rtype + "_" + pages.getPageNum() + "_" + pages.getPageSize();
		List<Map<String, String>> favoritesList = cacheService.getFavoritesList(7);
		String fid;
		if (favoritesList != null && favoritesList.size() > 0) {
			fid = favoritesList.get(0).get("cid");
		} else {
			fid = "2013310005";
		}
		return cacheService.getSupercouponGoodsList(DigestUtils.md5DigestAsHex(key.getBytes()), fid, pages);
	}

	@Override
	public List<CatGoodsCategoryResp> getCategoryList(Integer rtype, int vscode) {
		List<CatGoodsCategoryResp> resp = cacheService.getCategoryList(rtype, vscode);
		return resp;
	}

	@Override
	public ResultPage<TKTLJGoodsResp> tljGoodsList(String pid, Integer rtype, Pages pages, Integer ttype) {
		if (ttype == 0) {
			// 记录用户浏览淘礼金的时间
			asyncService.setTLJViewTime(pid);
		}
		String key = rtype + "_" + pages.getPageNum() + "_" + pages.getPageSize();

		ResultPage<TKTLJGoodsResp> result = cacheService.getTljGoodsList(key, pages);
		if (result == null) {
			return null;
		}

		List<TKTLJGoodsResp> list = result.getList();

		if (list != null && !list.isEmpty()) {
			Map<String, String> tkls = new HashMap<String, String>();
			List<TKTLJGoodsOrders> tljList = tklJGoodsOrdersRepository.findByPidAndTtype(pid, ttype);

			if (tljList != null && !tljList.isEmpty()) {
				tljList.forEach(action -> {
					tkls.put(action.getSid(), action.getTkl());
				});
			}
			result.setList(list.stream().map(mapper -> {
				if (tkls.containsKey(mapper.getNumIid())) {
					mapper.setTkl(tkls.get(mapper.getNumIid()));
				}
				return mapper;
			}).collect(Collectors.toList()));
		}

		return result;
	}

	@Override
	public TLJInfo getTLJInfo(String pid) {
		TLJInfo tljInfo = tljDao.selectOne(new CatDevUserInfo(pid), "getTljInfo");
		return tljInfo;
	}

	@Override
	@RedisSingle(key = "CAT_TLJ_CONVERT_+#pid_+#sid_+#ttype")
	public TKTLJConvertResp getTLJConvert(TKTLJGoodsResp goods, Integer ctype, Integer rtype, String vscode, String cid,
			String imei, String imsi, Long fcode, String sid, String pid, Integer ttype) {

		TKTLJConvertResp result = null;
//		double perface = (double) fcode / 100;
//		log.info("--淘礼金转链金额->{}-->{}", fcode, perface);
//		TbkDgVegasTljCreateResponse resultTemp = TBAPI.getInstance(10).getTLJGoodsConvert(Long.parseLong(sid),
//				perface + "", goods.getTljTime());
//
//		/* 一小时内不重复通知 */
//		if ("PRE_FREEZE_ASSET_ACCOUNT_ERROR".equals(resultTemp.getResult().getMsgCode())) {
//			String key = "CAT_TLJ_CONVERT_WAINING_MSG";
//			if (!redis9.hasKey(key)) {
//				RYSMSUtils.getInstance(1).sendWarningMS("18954109496", "九趣猫紧急通知", "九趣猫淘礼金不足,请及时充值");
//				RYSMSUtils.getInstance(1).sendWarningMS("13539997330", "九趣猫紧急通知", "九趣猫淘礼金不足,请及时充值");
//				redis9.opsForValue().set(key, "九趣猫淘礼金不足_" + TJKUtils.DateTime(), 1, TimeUnit.HOURS);
//			}
//			return null;
//		}
//
//		if (resultTemp != null && resultTemp.getResult().getModel() != null) {
//			RightsInstanceCreateResult resultUrl = resultTemp.getResult().getModel();
//			if (resultUrl != null && org.apache.commons.lang3.StringUtils.isNotBlank(resultUrl.getSendUrl())) {
//				// 获取淘口令
//				String pwd = TBAPI.getInstance(0).getTKL("淘礼金来啦", resultUrl.getSendUrl());
//				result = new TKTLJConvertResp(pwd, resultUrl.getSendUrl());
//				asyncService.insertTLJGoodsInfo(new TKTLJGoodsOrders(resultUrl.getRightsId(), resultUrl.getVegasCode(),
//						pid, sid, 0, fcode, pwd, ttype));
//				return result;
//			}
//		}
//		// 更新淘礼金商品下线
//		asyncService.offLineTLJGoods(sid, resultTemp.getResult().getMsgInfo());
		return result;
	}

	@Override
	public TKTLJGoodsResp getTLJGoods(String sid) {
		return gdao.selectOne(new TKTLJGoodsResp(sid));
	}

	@Override
	public String getGoodsWeShare(int ctype, int rtype, int stype, String pid, String p) {
		/**
		 * p1:pid 用户ID p2:stype 商品类型(0.淘宝、1.拼多多、2.京东) p3:p 淘宝参数 p4:p
		 * APP平台(0.九趣猫、1.淘淘集、2.一陶)
		 */
		String url = "https://mall.jiuqumao.cn/gshare/?p1=" + AesEncryptUtils.encryptBySalt(pid) + "&p2=" + stype
				+ "&p3=" + p + "&p4=" + ctype;
		try {
			url = URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + configs.getWxAppid()
				+ "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=1001#wechat_redirect";

		return path;
	}

	@Override
	public GoodsListResp getGoodsClipboardSearch(Integer ctype, Integer rtype, String vscode, String cid, String rid,
			String para) {
		GoodsListResp resp = null;
		String sword = para.trim();
		// 判断是否为淘口令
		String pattern = "([\\p{Sc}])\\w{8,12}([\\p{Sc}])";
		Pattern r = Pattern.compile(pattern);
		Matcher m = r.matcher(sword);
		// 如果为淘口令则直接调用转链接口查询商品信息
		if (m.find()) {
			resp = searchTbWord(rtype, sword);
			if (resp != null) {
				return resp;
			}
			// 修改是否含商品标题，此处是中文输入的【】
			Matcher mat = Pattern.compile("\\【([^}]*)\\】").matcher(sword);
			// 如果未查询到标题则直接返回
			if (mat.find()) {
				sword = mat.group(1);
				return getGoodsInfoByKeyword(sword);
			}
		} else {
			return getGoodsInfoByKeyword(sword);
		}
		return resp;
	}

	private GoodsListResp getGoodsInfoByKeyword(String sword) {
		DTKAPI api = DTKAPI.getInstance(0);
		ResultPage<GoodsListResp> resultPage = api.searchGoods("0", sword, "total_sales_des", "1", 10);
		if (resultPage != null && resultPage.getList() != null && resultPage.getList().size() > 0) {
			for (GoodsListResp obj : resultPage.getList()) {
				if (sword.equals(obj.getTitle())) {
					return obj;
				}
			}
		}
		return null;
	}

	@Override
	public CatHdkRatesUrlResp hdkRatesurl(String itemId) {
		return HdkAPI.getInstance().ratesurl(itemId);
	}
	
	

	@Override
	public CatHomeTemplateResp getHomeTemplateList(String pid, Integer sex) {
		List<CatBansResp> banners = cacheService.getBanners(sex);
		CatHomeTemplateResp templateResp = new CatHomeTemplateResp();
		templateResp.setBanner(new ArrayList<>());
		templateResp.setCategory(new ArrayList<>());
		for (CatBansResp catBansResp : banners) {
			if (catBansResp.getStype() == 0) {
				catBansResp.setEventId("7");
				templateResp.getBanner().add(catBansResp);
			} else if (catBansResp.getStype() == 1) {
				catBansResp.setEventId("8");
				templateResp.getCategory().add(catBansResp);
			}
		}
		List<CatDynamicBannerResp> dynamic = new ArrayList<>();
		if (!StringUtils.isEmpty(pid)) {
			// 1.1.6版本查询淘礼金信息
			TLJInfo tljInfo = tljDao.selectOne(new CatDevUserInfo(pid), "getTljInfo");
			if (tljInfo != null && tljInfo.getIsshow() == 1) {
				dynamic.add(new CatDynamicBannerResp("百万补贴", "http://img.jiuqumao.cn/imgs/home/ic_tlj_banner.webp", 0,
						1, 1, -2, "9"));
			} else {
				dynamic.add(new CatDynamicBannerResp("邀好友", "http://img.jiuqumao.cn/imgs/home/ic_banner_invite.webp", 1,
						1, 1, -2, "9"));
			}
		} else {
			dynamic.add(new CatDynamicBannerResp("", "", 0, 0, 0, 0, "9"));
		}
		templateResp.setDynamic(dynamic);

		// 设置达人说数据
		List<CatTalentInfoResp.TalentInfoData> talent = new ArrayList<>();
		CatTalentInfoResp talentInfo = cacheService.getTalentInfo(0);
		if (talentInfo != null && talentInfo.getNewdata() != null) {
			talent = talentInfo.getNewdata();
		}
		ArrayList<CatHomeTemplateResp.MarqueeData> marqueeData = new ArrayList<>();
		marqueeData.add(new CatHomeTemplateResp.MarqueeData(talent));
		templateResp.setMarquee(marqueeData);
		return templateResp;
	}

	@Override
	public ResultPage<HdkGoodsItem> getHdkKeywordItems(String keyword, Integer cid, Integer sort, Integer pageNum,
			Integer pageSize) {
		String key = keyword + "_" + cid + "_" + sort + "_" + pageNum + "_" + pageSize;
		return cacheService.getHdkKeywordItems(DigestUtils.md5DigestAsHex(key.getBytes()), keyword, cid, sort, pageNum,
				pageSize);
	}

	@Override
	public CatTalentInfoResp getTalentInfo(Integer talentcat) {
		// TODO 获取达人说数据
		return cacheService.getTalentInfo(talentcat);
	}

	@Override
	public CatTalentArticleResp getTalentArticle(Integer id) {
		// TODO 获取达人说文章数据
		HdkAPI api = HdkAPI.getInstance();
		return api.getTalentArticle(id);
	}

	@Override
	public ResultPage<HdkGoodsItem> getHdkItemList(Integer nav, Integer cid, Integer sort, Integer pageNum,
			Integer pageSize) {
		String key = nav + "_" + cid + "_" + sort + "_" + pageNum + "_" + pageSize;
		return cacheService.getHdkItemList(DigestUtils.md5DigestAsHex(key.getBytes()), nav, cid, sort, pageNum,
				pageSize);
	}

	@Override
	public List<CatDouYinVideoResp> getHdkDuoyinItems(String itemId, Integer pageNum) {
		// TODO Auto-generated method stub
		String key = itemId + "_" + pageNum;
		return cacheService.getHdkDuoyinItems(DigestUtils.md5DigestAsHex(key.getBytes()), itemId, pageNum);
	}

	@Override
	public TKConvertResp getGoodsConvertInfo(Integer rtype, String vscode, String sid) {
		WeiYiAPI api = WeiYiAPI.getInstance(40);
		// 调用高佣转链API
		TKConvertResp tkConvert = api.getTKConvert(sid, "");
		return tkConvert;
	}

	@Override
	public List<HdkGoodsItem> hdkRankList(Integer rtype, Integer stype, Integer back, Integer min_id, Integer cid,
			Integer item_type) {
		String key = rtype + "_" + stype + "_" + back + "_" + min_id + "_" + cid + "_" + item_type;
		List<HdkGoodsItem> resultTemp = cacheService.hdkRankList(key, stype, back, min_id, cid, item_type);
		return resultTemp;
	}

	@Override
	public List<CatHdkDuoyinResp> getHdkDuoyinData(Integer rtype, Integer cat_id, Integer min_id, Integer back) {
		return HdkAPI.getInstance().getHdkDuoyinData(cat_id, min_id, back);
	}

	
	/**
	 * 淘宝店铺商品查询
	 */
	@Override
	public ResultPage<CatShopItemResp> getShopItem(Integer ctype,Integer rtype,String pageno, String userId) {
		// TODO Auto-generated method stub
//		int type = 20;
//		ctype = 0;
//		type = (ctype + 1) * 10 + rtype;
//		WeiYiAPI api = WeiYiAPI.getInstance(type);
//
//		// 调用高佣转链API
//		ResultPage<CatShopItemResp> shopItemResp = api.getShopItem(pageno,userId);
//		return shopItemResp;
		return null;
	}
	
	/**
	 * 查询淘宝天猫店铺商品优惠券 
	 */
	@Override
	public CatShopCouponInfo getShopCoupon(Integer rtype,Integer ctype,String itemId, String sellerId) {
		// TODO Auto-generated method stub
		int type = 20;
		ctype = 0;
		type = (ctype + 1) * 10 + rtype;
		WeiYiAPI api = WeiYiAPI.getInstance(type);

		// 调用高佣转链API
		CatShopCouponInfo shopCouponInfo = api.getShopsCoupon(itemId,sellerId);
		
		return shopCouponInfo;
	}
}
